package com.example.shrimp.frame;

import android.content.res.AssetManager;
import com.example.shrimp.App;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.HashMap;

public class AppConfig {
    private AppConfig(){
        try {
            initData();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static AppConfig instance;

    public static AppConfig getInstance() {
        if (instance == null){
            instance = new AppConfig();
        }
        return instance;
    }

    public MainTabsEntity mainTabsEntity;
    public HashMap<String, DestinationEntity> destinationMap;

    //读取assets下JSON字符串的方法
    private String readAsstes(String path,AssetManager assets) throws IOException {
        String result = null;
        InputStream inputStream = assets.open(path);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line ;
        StringBuffer buffer = new StringBuffer();
        while((line = bufferedReader.readLine())!=null){
            buffer.append(line);
        }
        bufferedReader.close();
        result = buffer.toString();
        return result;
    }

    private void initData() throws IOException {
        AssetManager assets = App.getInstance().getAssets();
        String mainResult = readAsstes("main_tabs_config.json",assets);
        String destinationResult = readAsstes("destination.json",assets);
        mainTabsEntity = new Gson().fromJson(mainResult,MainTabsEntity.class);
        Type type = new TypeToken<HashMap<String,DestinationEntity>>(){}.getType();
        destinationMap = new Gson().fromJson(destinationResult,type);
    }

}
